package com.abc.robot01.fragment

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDefaults
import androidx.compose.material3.DatePickerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Gray
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.abc.robot01.R
import com.abc.robot01.activity.BaoJiaActivity
import com.abc.robot01.activity.CancelButton
import com.abc.robot01.activity.ConfirmButton
import com.abc.robot01.activity.ConfirmButton2
import com.abc.robot01.activity.ConfirmButton3
import com.abc.robot01.activity.CustomerRenderDetails
import com.abc.robot01.activity.H5Activity
import com.abc.robot01.activity.MYBLACK
import com.abc.robot01.activity.MYBLACK_Percent10
import com.abc.robot01.activity.MYBLACK_Percent40
import com.abc.robot01.activity.MYBLACK_Percent5
import com.abc.robot01.activity.MYBLUE
import com.abc.robot01.activity.MYWhilte_Percent40
import com.abc.robot01.activity.MyButton01
import com.abc.robot01.activity.MyFont_Size
import com.abc.robot01.activity.SystemFragmentBackground
import com.abc.robot01.activity.mysp
import com.abc.robot01.activity.px
import com.abc.robot01.activity.startActivity
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.vivemodel.SystemMessageFragmentViewModel
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 */
class SystemMessageFragment2 : Fragment() {
    private val viewModel: SystemMessageFragmentViewModel by viewModels()
    val TAG = "系统信息"
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val composeView = ComposeView(requireContext()).apply {
            setContent {
                var w by remember { mutableStateOf(864) }
                var p by remember { mutableStateOf(866) }
                val show   by remember {
                    viewModel.show
                }
                val startDate by remember { viewModel.startDate }
                val endDate by remember {  viewModel.endDate }
                val  datePickerState  = rememberDatePickerState()
                SystemFragmentBackground {
                    Column(modifier = Modifier.offset(x = 30.px, y = 30.px)) {
                        Row {
                            ConfirmButton3(text = "公司信息") {
                            }
                            Spacer(modifier = Modifier.width(30.px))
                            ConfirmButton3(
                                text = "本机信息",
                                textColor = MYBLACK.copy(alpha = 0.6f),
                            ) {
                            }
                        }
                        Spacer(modifier = Modifier.height(30.px))
                        Row{
                        Row(
                            modifier = Modifier
                                .size(500.px, 50.px)
//                                .border(BorderStroke(2.px, MYBLUE))
                                .background(color = MYBLACK_Percent5,
//                                    Color(0xFFFFFFFF),
                                    shape = RoundedCornerShape(10.px)
                                )
                                .padding(start = 34.px, end = 10.px),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            BasicText(
                                modifier = Modifier.width(124.px)
                                    .clickable {
                                   viewModel.show.value = true
                                    viewModel.isLeft.value = true
                                        if(startDate!=0L){
                                            datePickerState.selectedDateMillis= startDate
                                        }
                                },
                                text = if (startDate==0L) "开始日期" else formatDate(startDate),
                                style = TextStyle(
                                    color = MYBLACK_Percent40,
                                    textAlign= TextAlign.Center,
                                    fontWeight = FontWeight.Normal,
                                    fontSize = MyFont_Size,
                                )
                            )
                            Spacer(modifier = Modifier.width(54.px))
                            Image(
                                painter = painterResource(id = R.drawable.toright),
                                contentDescription = "Image",
                                contentScale = ContentScale.Crop,
                            )
                            Spacer(modifier = Modifier.width(54.px))
                            BasicText(
                                modifier = Modifier.clickable {
                                    viewModel.show.value = true
                                    viewModel.isLeft.value = false
                                    if(endDate!=0L){
                                        datePickerState.selectedDateMillis= endDate
                                    }
                                },
                                text = if (endDate==0L) "结束日期" else formatDate(endDate),
                                style = TextStyle(
                                    color = MYBLACK_Percent40,
                                    fontWeight = FontWeight.Normal,
                                    fontSize = MyFont_Size,
                                )
                            )
                            Spacer(modifier = Modifier.weight(54f))
                            Image(
                                modifier = Modifier.size(30.px, 30.px),
                                painter = painterResource(id = R.drawable.frame88), // 替换为你的图片资源ID
                                contentDescription = null,
                            )
                        }
                            Spacer(modifier = Modifier.width(30.px))
                            MyButton01(
                                text = "重置",
                                size = DpSize(108.px, 48.px),
                                textColor = MYBLACK,
                                containerColor = MYBLACK_Percent10,
                                shape = RoundedCornerShape(10.px)
                            ) {
                              viewModel.reset()
                                viewModel.load()
                            }
                            Spacer(modifier = Modifier.width(20.px))
                            MyButton01(
                                text = "确认", size = DpSize(108.px, 48.px), textColor = Color.White,
                                containerColor = MYBLUE, shape = RoundedCornerShape(10.px)
                            ) {
                                viewModel.load()
                            }
                        }
                        Spacer(modifier = Modifier.height(10.px))
                        DataList()
                    }
                }
                if (show) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black.copy(alpha = 0.5f))
                    )
                MaterialTheme {
                    DatePickerDocked2(datePickerState)
                }
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Row(
                        modifier = Modifier
                            .width(w.px)
                            .offset(y = 300.px)
                            .background(Color.White)
                            .padding(10.px),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        CancelButton{
                            viewModel.show.value=false
                        }
                        Spacer(modifier = Modifier.width(60.px))
                        ConfirmButton2{
                            viewModel.selectedDateMillis.value=datePickerState.selectedDateMillis!!
                            if(viewModel.isLeft.value) {
                                viewModel.startDate.value = datePickerState.selectedDateMillis!!
                            }else{
                                viewModel.endDate.value = datePickerState.selectedDateMillis!!
                            }
                            viewModel.show.value=false
                        }
                    }
                }
                    if(1==2) {
                        Column {
                            Button(onClick = {
                                w += 1;
                                /*TODO*/
                            }) {
                                Text(text = "add:" + w)
                            }

                            Button(onClick = {
                                w -= 1;
                                /*TODO*/
                            }) {
                                Text(text = "add2:" + w)
                            }
                        }
                    }
                    }
            }
        }
        return composeView
    }



    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun DatePickerDocked2(datePickerState: DatePickerState) {
//    val scrollState = rememberScrollState()
        val scrollState = ScrollState(489)
        Column(
            verticalArrangement = Arrangement.spacedBy(16.dp),
            modifier = Modifier
                .verticalScroll(scrollState)
                .fillMaxSize()
        ) {
//                    DatePickerModal()
            MaterialTheme {
                DatePickerDocked(datePickerState)
            }
        }
        Log.e("DataPickerDemo",""+scrollState.value)
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    private  fun DatePickerDocked(datePickerState: DatePickerState) {
        Log.e(TAG,""+  datePickerState.selectedDateMillis)
//        datePickerState.selectedDateMillis?.let {
//
//        }
        Box(
            modifier = Modifier
                .fillMaxSize()
//            .offset(x = -616.px)
        ) {
            DatePicker(
                colors  = DatePickerDefaults.colors().copy(containerColor = Color.White),
                modifier = Modifier
                    .scale(0.45f)
                    .background(Color.White),
                state = datePickerState,
                showModeToggle = false
            )
        }
    }


    private fun remove(dataList: MutableList<Item147>, itemToRemove: Item147) {
        if (dataList.size == 2) {
            dataList.clear();
            return
        }
        if (dataList.isNotEmpty()) {
            // Find the index of the item to remove
            val index = dataList.indexOf(itemToRemove)
            if (index != -1) {
                // Check if the previous item is a title
                val hasPreviousTitle = index > 0 && dataList[index - 1].isTitle

                // Check if the next item is a title
                val hasNextTitle = index < dataList.size - 1 && dataList[index + 1].isTitle

                // Remove the item
                dataList.removeAt(index)

                // If both previous and next items are titles, remove the previous title
                if (hasPreviousTitle && hasNextTitle) {
                    dataList.removeAt(index - 1)
                }
            }
        }
    }

    @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
    @Composable
    fun LazyItemScope.ItemRow(dataList: MutableList<Item147>, item: Item147) {
        Log.e(TAG, "ItemRow:" + item)
        if (item.isTitle) {
            Text(
                text = item.name,
                style = MaterialTheme.typography.bodyMedium.copy(
                    fontSize = 23.mysp,
                    fontWeight = FontWeight.Normal,
                    color = MYBLACK
                ),
                modifier = Modifier
                    .animateItemPlacement()
                    .background(Color.Transparent)
                    .padding(vertical = 0.dp)
            )
            return
        }
//        val dismissBoxState = rememberSwipeToDismissBoxState(positionalThreshold = { 500f })
//        Log.e(TAG,"dismissBoxState.currentValue:"+ dismissBoxState.currentValue);
//        Log.e(TAG, "dismissBoxState.progress:" + dismissBoxState.progress);
//        Log.e(TAG,"dismissBoxState.targetValue:"+ dismissBoxState.targetValue);
//        SwipeToDismissBox(
//            modifier = Modifier.animateItemPlacement(),
//            state = dismissBoxState,
//            backgroundContent = {
//                Box(
//                    modifier = Modifier
//                        .fillMaxSize()
//                        .background(Color.Transparent),
//                    contentAlignment = Alignment.CenterEnd
//                ) {
//                    if (dismissBoxState.progress != 1.0f) {
//                        val alphaValue = (dismissBoxState.progress / 0.07).coerceIn(0.0, 1.0)
//                        Box(
//                            modifier = Modifier
//                                .height(100.px)
//                                .width(120.px)
//                                .background(Color.Red.copy(alpha = alphaValue.toFloat()))
//                        ) {
//                            Text(
//                                "删除",
//                                color = Color.White.copy(alpha = alphaValue.toFloat()),
//                                fontSize = MyFont_Size,
//                                modifier = Modifier.align(Alignment.Center)
//                            )
//                        }
//                    }
//                }
//            },
//            content = {
                Box(
                    modifier = Modifier
                        .clickable {
                            activity?.startActivity<H5Activity>() {
                                putExtra("id", item.id)
                                putExtra("url", item.url)
                            }
//                        startActivity<BaoJiaActivity>() {
//                            putExtra("index", 2)
//                        }
                        }
                        .fillMaxWidth()
                        .background(
                            color = MYWhilte_Percent40, // Background color for the item
                            shape = if (item.position == 0) RoundedCornerShape(
                                8.dp,
                                8.dp,
                                0.dp,
                                0.dp
                            ) else if (item.position == 1) RoundedCornerShape(0) else RoundedCornerShape(
                                0.dp,
                                0.dp,
                                8.dp,
                                8.dp
                            ) // Rounded corners for the item
                        )
                        .padding(vertical = 8.dp, horizontal = 16.dp)
                        .padding(bottom = 0.dp) // Space between items
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(), // Make Row fill the width of its container
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Spacer(modifier = Modifier.width(20.px))
                        Image(
                            painter = painterResource(if (item.success) R.drawable.a2 else R.drawable.a4),
                            contentDescription = ""
                        )
                        Spacer(modifier = Modifier.width(30.px))
                        Box(
                            contentAlignment = Alignment.Center,
                            modifier = Modifier.wrapContentSize()
                        ) {
                            Image(painter = painterResource(R.drawable.a), contentDescription = "")
                            Text(
                                text = if (item.success) "渲染成功" else "渲染失败",
                                style = MaterialTheme.typography.bodyMedium.copy(
                                    fontSize = 20.mysp,
                                    fontWeight = FontWeight.Normal
                                ),
                                color = if (item.success) Color.Blue else Color.Red
                            )
                        }
                        Spacer(modifier = Modifier.width(30.px))
                        Text(
                            text = item.device,
                            maxLines=1,
                            textAlign = TextAlign.Start,
                            modifier = Modifier.width(180.px),
                            style = MaterialTheme.typography.bodyMedium.copy(
                                fontSize = 23.mysp,
                                fontWeight = FontWeight.Normal
                            ),
                        )
                        Spacer(modifier = Modifier.width(30.px))
                        Text(
                            text = item.name,
                            style = MaterialTheme.typography.bodyMedium.copy(
                                fontSize = 23.mysp,
                                fontWeight = FontWeight.Normal
                            ),
                        )
                        Spacer(modifier = Modifier.weight(1f))
                        Text(
                            text = reformatDate(item.date),
                            style = MaterialTheme.typography.bodyMedium.copy(
                                fontSize = 23.mysp,
                                fontWeight = FontWeight.Normal
                            ),
                        )
                    }

                }
//            }
//        )
//        LaunchedEffect(dismissBoxState.currentValue) {
//            if (dismissBoxState.currentValue == SwipeToDismissBoxValue.EndToStart) {
//                remove(dataList, item)
//                Log.e(TAG, "EndToStart");
//            }
//        }
    }

    @Composable
    fun DataList() {
        val items0 by viewModel.customerList.collectAsState()

        // 用于存储按月分组的结果
        val groupedData = mutableMapOf<String, MutableList<RetrofitService.RenderItem>>()
        // 日期格式化器
        val formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss")
        for (item in items0) {
            if (item.endTime.isNotEmpty()) {
                // 解析日期并提取年和月
                val date = LocalDate.parse(item.endTime, formatter)
                val key = "${date.year}年${date.monthValue}月"
                // 将项目添加到相应的分组中

                groupedData.getOrPut(key) { mutableListOf() }.add(item)
            }
        }

        val dataList2 = mutableListOf<Item147>()

        // 打印分组结果
        for ((key, items) in groupedData) {
            Log.e(CustomerRenderDetails.TAG, "分组: $key")
            dataList2.add(Item147(position = -1, isTitle = true, name = key))
            for (item in items) {
                dataList2.add(
                    Item147(
                        id = item.id,
                        position = 1,
                        isTitle = false,
                        success = item.status == 3,
                        name = item.name,
                        date = item.endTime,
                        url = item.url,
                        device = item.robotName?:"无名称"
                    ).also {
                        Log.e(TAG, "url:" + it.url);


                    }
                )
                Log.e(CustomerRenderDetails.TAG, "  - ${item.name} (ID: ${item.id})")
            }
        }
        val items = dataList2
        Log.e(TAG, "dataList:" + dataList2.size);
        val size = remember { dataList2.size };

        Column {
            LazyColumn {
                itemsIndexed(items, key = { _, item -> item.id }) { index, item ->
                    val isLastItem = index == items.lastIndex
                    ItemRow(items, item);
                    if (isLastItem.not() && item.isTitle.not())
                        if (index < items.lastIndex && items[index + 1].isTitle.not()) {
                            HorizontalDivider(
                                modifier = Modifier.fillMaxWidth(),
                                thickness = 1.px,
                                color = MYBLACK_Percent10
                            )
                        }
                }
            }
        }
    }

    private fun showDatePickerDialog(result: (String) -> Unit) {
        val calendar: Calendar = Calendar.getInstance()
        val year: Int = calendar.get(Calendar.YEAR)
        val month: Int = calendar.get(Calendar.MONTH)
        val day: Int = calendar.get(Calendar.DAY_OF_MONTH)

        // Create a DatePickerDialog
        val datePickerDialog = DatePickerDialog(
            requireContext(),
            { view: DatePicker?, selectedYear: Int, selectedMonth: Int, selectedDay: Int ->
                val selectedDate =
                    "" + selectedYear + "/" + (selectedMonth + 1) + "/" + selectedDay.toString()
                result(selectedDate)
            },
            year, month, day
        )
        datePickerDialog.show()
    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG, "onResume");
    }

    override fun onStart() {
        super.onStart()
        Log.e(TAG, "onStart");
    }

    override fun onPause() {
        super.onPause()
        Log.e(TAG, "onPause");
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG, "onStop");
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy");
    }

    override fun onDetach() {
        super.onDetach()
        Log.e(TAG, "onDetach");
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.load()
        Log.e(TAG, "onCreate");
    }

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        Log.e(TAG, "onAttach activity");
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.e(TAG, "onAttach Context");
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    companion object {
        val TAG = "SystemMessageFragment"
    }
}

        data class Item147(
            /**
             *   0 为开始
             *   1 为中间
             *   2 为末尾.
             */
            val position:Int = -1,
            val id:String = "0" ,
            val url:String? = "" ,
            val isTitle: Boolean  = false,
            val count: Int  = 0,
            val success: Boolean = true,
            val device: String = "设备001",
            val name: String = "沿海地中海风格三室两厅",
            val date: String = "2023年7月23日 15:12"
        )


fun formatDate(timestamp: Long): String {
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    val date = Date(timestamp)
    return sdf.format(date)
}

fun reformatDate(input: String): String {
    val inputFormat = SimpleDateFormat("yyyy-M-d HH:mm:ss", Locale.getDefault())
    val outputFormat = SimpleDateFormat("yyyy年M月d日 HH:mm:ss", Locale.getDefault())

    val date = inputFormat.parse(input) // 将输入字符串解析为 Date 对象
    return outputFormat.format(date!!) // 将 Date 格式化为目标字符串
}